import cv2, json
import sys
import numpy as np
import time
import sys
import os, base64
from threading import Thread

sys.path.append("..")


class SavePic:
    def __init__(self):
        # 顺着看
        self.l="rtsp://admin:1qaz@WSX@192.168.2.169:554/h264/ch1/main/av_stream"
        self.r="rtsp://admin:1qaz@WSX@192.168.2.168:554/h264/ch1/main/av_stream"
        self.img_dir="./cali_img"
        # self.img_dir="./img"

    def read_shape(self, fname='./rectifyresult/1.png'):
        img=cv2.imread(fname)
        gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray_shape=gray.shape[::-1]
        print(gray_shape)

    
    def resize(self,img,scale):
        width=int(img.shape[1] * scale / 100)
        height=int(img.shape[0] * scale/ 100)
        dim=(width, height)
        resized=cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
        return resized
    def save_camera(self):
        os.makedirs(f"{self.img_dir}/left", exist_ok=True)
        os.makedirs(f"{self.img_dir}/right", exist_ok=True)
        start=time.time()
        while True:
            capr=cv2.VideoCapture(self.r)
            capl=cv2.VideoCapture(self.l)
            successl, imagel=capl.read()
            successr, imager=capr.read()
            
            if not (successl and successr): continue
            print(imagel.shape, imager.shape)
            now=time.time()
            elapsed=now - start
            if elapsed>5:
                start=now
                filel=os.path.abspath(f"{self.img_dir}/left/{start}.jpg")
                filer=os.path.abspath(f"{self.img_dir}/right/{start}.jpg")
                print("save pic")
                cv2.imwrite(filel, imagel)
                cv2.imwrite(filer, imager)
            
            # or horizontal (next to each other):
            final = cv2.hconcat([self.resize(imagel,50), self.resize(imager,50)])
            
            cv2.imshow("frame", final)
            cv2.waitKey(1)
        capr.release()
        capl.release()
        cv2.destroyAllWindows()


if __name__=='__main__':
    s=SavePic()
    s.save_camera()
